<template>
  <div class="app-container">
    <!-- 页面头部 -->
    <PageHeader back-text="返回合同回款统计列表" back-type="back" :title="contractData?.contractName || '加载中...'" />

    <!-- 合并的合同回款信息卡片 -->
    <el-card class="box-card contract-receive-card mb-6" shadow="hover">
      <template #header>
        <div class="card-header">
          <el-icon>
            <Document />
          </el-icon>
          <span>合同回款信息</span>
          <div style="margin-left:8px;display:flex;align-items:center;">
            <dict-tag :options="pro_receive_is_arrive" :value="contractData?.isArrive || ''" />
          </div>
        </div>
      </template>

      <!-- 合同信息（合并基础信息与回款状态信息） -->
      <div class="info-section">
        <div class="section-title">
          <el-icon>
            <InfoFilled />
          </el-icon>
          <span>合同回款详情</span>
        </div>
        <el-descriptions :column="3" border>
          <el-descriptions-item label="合同名称">
            <span class="contract-name-text">{{ contractData?.contractName || '-' }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="合同编号">
            <span class="contract-number-text">{{ contractData?.contractNumber || '-' }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="业主单位">
            {{ contractData?.ownerUnit || '-' }}
          </el-descriptions-item>
          <!-- 第二排：执行总裁、项目负责人、收款负责人 -->
          <el-descriptions-item label="执行总裁">
            <span class="text-overflow name-left">{{ contractData?.proPresidentsName || '-' }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="项目负责人">
            <span class="text-overflow name-left">{{ contractData?.proLeadersName || '-' }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="收款负责人">
            <span class="text-overflow name-left">{{ contractData?.receiveLeadersName || '-' }}</span>
          </el-descriptions-item>
          <!-- 第三排：金额信息 -->
          <el-descriptions-item label="合同总金额">
            <span class="amount-text contract-amount">{{ formatAmount(contractData?.conAmount) }}元</span>
          </el-descriptions-item>
          <el-descriptions-item label="已达节点总金额">
            <span class="amount-text arrived-amount">{{ formatAmount(getStat('arrivedNodeAmount')) }}元</span>
          </el-descriptions-item>
          <el-descriptions-item label="已回款金额">
            <span class="amount-text received-amount">{{ formatAmount(contractData?.receivedAmount) }}元</span>
          </el-descriptions-item>
          <el-descriptions-item label="已开票未回款金额">
            <span class="amount-text">{{ formatAmount(getStat('noReceiveAmount')) }}元</span>
          </el-descriptions-item>
          <!-- 第四排：剩余金额信息 -->
          <el-descriptions-item label="已达节点剩余应收款金额">
            <span class="amount-text remaining-amount">{{ formatAmount(getStat('surplusNodeReceiveAmount')) }}元</span>
          </el-descriptions-item>
          <el-descriptions-item label="剩余合同金额">
            <span class="amount-text surplus-con-amount">{{ formatAmount(getStat('surplusConAmount')) }}元</span>
          </el-descriptions-item>
          <el-descriptions-item label="合同是否达到回款节点">
            <dict-tag :options="pro_receive_is_arrive" :value="receiveForm.isArrive || ''" />
          </el-descriptions-item>
          <el-descriptions-item label="上次情况和下一步计划" :span="3">
            <el-input v-model="lastReceiveCase" disabled placeholder="暂无历史记录" type="textarea" :rows="2" />
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <!-- 回款信息编辑表单 -->
      <div class="edit-section">
        <div class="section-title">
          <el-icon>
            <Edit />
          </el-icon>
          <span>合同回款信息编辑</span>
        </div>
        <el-form ref="receiveFormRef" :model="receiveForm" :rules="receiveFormRules" label-width="140px">
          <!-- 第一行：收款状态 -->
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="收款状态" prop="receiveStatus">
                <el-select v-model="receiveForm.receiveStatus" placeholder="请选择收款状态" style="width: 100%">
                  <el-option v-for="item in pro_receive_node_status" :key="item.value" :label="item.label"
                    :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <!-- 预留位置，保持布局平衡 -->
            </el-col>
          </el-row>

          <!-- 第二行：金额相关字段 -->
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="已达节点总金额">
                <MoneyInput v-model="receiveForm.arrivedNodeAmount" :min="0" style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="已开票未回款金额">
                <MoneyInput v-model="receiveForm.noReceiveAmount" :min="0" style="width: 100%" />
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 第三行：文本域字段 -->
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="最新收款情况及下一步收款计划" prop="latestReceiveCase">
                <el-input v-model="receiveForm.latestReceiveCase" type="textarea" :rows="3"
                  placeholder="请输入最新收款情况及下一步计划" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <el-input v-model="receiveForm.remark" type="textarea" :rows="2" placeholder="请输入备注" />
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 操作按钮：固定在本编辑板块右下角 -->
          <el-form-item class="form-actions form-actions-bottom" label-width="0">
            <el-button type="primary" size="large" @click="saveReceiveInfo" :loading="saveReceiveLoading"
              style="min-width: 120px">保存</el-button>
            <el-button size="large" @click="handleReset" style="min-width: 120px">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>



    <!-- 项目回款信息层级查看 -->
    <el-card class="box-card project-receive-card mb-6" shadow="hover">
      <template #header>
        <div class="card-header">
          <el-icon>
            <List />
          </el-icon>
          <span>项目回款信息查看</span>
        </div>
      </template>

      <!-- 第一层：项目列表 -->
      <div v-loading="projectLoading" class="project-list">
        <div v-if="projectList.length === 0" class="empty-state">
          <el-empty description="暂无项目信息" />
        </div>

        <!-- 表头 -->
        <div v-if="projectList.length > 0" class="list-header">
          <div class="header-cell header-name left-align">项目名称</div>
          <div class="header-cell header-number">项目编号</div>
          <div class="header-cell header-president">执行总裁</div>
          <div class="header-cell header-leader">项目负责人</div>
          <div class="header-cell header-receive-leader">收款负责人</div>
          <div class="header-cell header-status">项目是否达到回款节点</div>
          <div class="header-cell header-action">操作</div>
        </div>

        <!-- 项目列表项 -->
        <div v-for="(project, index) in projectList" :key="project.proId" class="project-item">
          <!-- 项目主行 -->
          <div class="project-row">
            <div class="project-cell project-name left-align">
              <span class="text-overflow">{{ project.proName || '-' }}</span>
            </div>
            <div class="project-cell project-number">
              <span>{{ project.proNumber || '-' }}</span>
            </div>
            <div class="project-cell project-president">
              <span class="text-overflow">{{ project.proPresidentsName || '-' }}</span>
            </div>
            <div class="project-cell project-leader">
              <span class="text-overflow">{{ project.proLeadersName || '-' }}</span>
            </div>
            <div class="project-cell project-receive-leader">
              <span class="text-overflow">{{ project.receiveLeadersName || '-' }}</span>
            </div>
            <div class="project-cell project-status">
              <dict-tag :options="pro_receive_is_arrive" :value="project.isArrive || ''" />
            </div>
            <div class="project-cell project-action expand-cell">
              <div class="expand-button" :class="{ 'expanded': project.expanded }"
                @click="toggleProjectExpand(project)">
                <span class="expand-text">{{ project.expanded ? '收起' : '查看回款节点' }}</span>
                <el-icon class="expand-arrow" :class="{ 'rotated': project.expanded }">
                  <ArrowDown />
                </el-icon>
              </div>
            </div>
          </div>

          <!-- 展开的回款节点内容 -->
          <div v-show="project.expanded" class="expand-content">
            <div class="receive-header">
              <div class="receive-header-left">
                <el-icon class="receive-icon">
                  <Money />
                </el-icon>
                <span class="receive-title">付款节点信息查看</span>
                <el-tag size="small" type="info">{{ (project.receiveList || []).length }} 个节点</el-tag>
              </div>
            </div>

            <!-- 回款节点列表 -->
            <div class="receive-list" v-loading="project.receiveLoading">
              <el-table :data="project.receiveList" border style="width: 100%" size="small"
                :row-class-name="receiveRowClassName" class="receive-table-fixed" :header-cell-style="{'text-align':'center'}">
                
                <!-- 1. 节点标题（2） -->
                <el-table-column label="付款节点" align="left" width="1000">
                  <template #default="scope">
                    <span class="node-title-text two-line-clamp">{{ scope.row.nodeTitle || '-' }}</span>
                  </template>
                </el-table-column>
                <!-- 2. 是否到达回款节点（150） -->
                <el-table-column label="是否到达回款节点" prop="isArrive" width="150" align="center">
                  <template #default="scope">
                    <dict-tag :options="pro_receive_is_arrive" :value="scope.row.isArrive || ''" />
                  </template>
                </el-table-column>
                <!-- 3. 收款负责人（150） -->
                <el-table-column label="收款负责人" prop="nodeLeadersName" width="150" align="center" />
                <!-- 4. 备注（1） -->
                <el-table-column label="备注" prop="remark" :show-overflow-tooltip="true" />
              </el-table>

              <div v-if="!project.receiveList || project.receiveList.length === 0" class="no-data">
                <el-empty description="暂无回款节点信息" :image-size="60" />
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-card>





    <!-- 历史回款记录（可收起） 放到页面最下方 -->
    <el-card class="box-card history-record-card mb-6" shadow="hover">
      <template #header>
        <div class="card-header collapsible" @click="historyCollapsed = !historyCollapsed">
          <div style="display:flex;align-items:center;gap:8px;">
            <el-icon>
              <Clock />
            </el-icon>
            <span>历史回款记录</span>
          </div>
          <el-icon class="expand-arrow" :class="{ rotated: !historyCollapsed }">
            <ArrowDown />
          </el-icon>
        </div>
      </template>
      <div v-show="!historyCollapsed">
        <!-- 合并：回款统计变化图表 -->
        <div ref="historyChartRef" class="history-chart"></div>
        <el-table :data="historyReceiveList" border stripe v-loading="historyLoading" height="200"
          :row-class-name="historyRowClassName">
          <el-table-column label="记录人" prop="createName" width="120" align="center">
            <template #default="scope">
              <span>{{ scope.row.createName || '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="记录时间" prop="createTime" width="150" align="center">
            <template #default="scope">
              <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="收款状态" prop="receiveStatus" width="120" align="center">
            <template #default="scope">
              <template v-if="scope.row._editing">
                <el-select v-model="scope.row.receiveStatus" placeholder="请选择" size="small" style="width: 110px">
                  <el-option v-for="it in pro_receive_node_status" :key="it.value" :label="it.label"
                    :value="it.value" />
                </el-select>
              </template>
              <template v-else>
                <div @dblclick="enableEditHistoryRow(scope.row)">
                  <dict-tag :options="pro_receive_node_status" :value="scope.row.receiveStatus || ''" />
                </div>
              </template>
            </template>
          </el-table-column>
          <el-table-column label="是否到达回款节点" prop="isArrive" width="150" align="center">
            <template #default="scope">
              <dict-tag :options="pro_receive_is_arrive" :value="scope.row.isArrive || ''" />
            </template>
          </el-table-column>
          <el-table-column label="已达回款的节点" prop="receiveNodes" show-overflow-tooltip width="200">
            <template #default="scope">
              <div @dblclick="enableEditHistoryRow(scope.row)">{{ scope.row.receiveNodes || '-' }}</div>
            </template>
          </el-table-column>
          <el-table-column label="已达节点总金额" prop="arrivedNodeAmount" width="170" align="center">
            <template #default="scope">
              <template v-if="scope.row._editing">
                <MoneyInput v-model="scope.row.arrivedNodeAmount" :min="0" />
              </template>
              <template v-else>
                <span class="amount-text" @dblclick="enableEditHistoryRow(scope.row)">{{
                  formatAmount(scope.row.arrivedNodeAmount) }}元</span>
              </template>
            </template>
          </el-table-column>
          <el-table-column label="已收款金额" prop="receivedAmount" width="150" align="center">
            <template #default="scope">
              <span class="amount-text">{{ formatAmount(scope.row.receivedAmount) }}元</span>
            </template>
          </el-table-column>
          
          <el-table-column label="已达节点应收款金额" prop="surplusAmount" width="170" align="center">
            <template #default="scope">
              <template v-if="scope.row._editing">
                <MoneyInput v-model="scope.row.surplusAmount" :min="0" />
              </template>
              <template v-else>
                <span class="amount-text" @dblclick="enableEditHistoryRow(scope.row)">{{
                  formatAmount(scope.row.surplusAmount) }}元</span>
              </template>
            </template>
          </el-table-column>
          <el-table-column label="已开票未回款金额" prop="noReceiveAmount" width="170" align="center">
            <template #default="scope">
              <template v-if="scope.row._editing">
                <MoneyInput v-model="scope.row.noReceiveAmount" :min="0" />
              </template>
              <template v-else>
                <span class="amount-text" @dblclick="enableEditHistoryRow(scope.row)">{{
                  formatAmount(scope.row.noReceiveAmount) }}元</span>
              </template>
            </template>
          </el-table-column>
          <el-table-column label="最新收款情况" prop="latestReceiveCase" width="300" align="left">
            <template #default="scope">
              <template v-if="scope.row._editing">
                <el-input v-model="scope.row.latestReceiveCase" type="textarea" :rows="3" />
              </template>
              <template v-else>
                <div class="text-overflow left-text" @dblclick="enableEditHistoryRow(scope.row)"
                  :title="scope.row.latestReceiveCase">{{ scope.row.latestReceiveCase || '-' }}</div>
              </template>
            </template>
          </el-table-column>
          <el-table-column label="备注" prop="remark" width="300" align="left">
            <template #default="scope">
              <template v-if="scope.row._editing">
                <el-input v-model="scope.row.remark" type="textarea" :rows="3" />
              </template>
              <template v-else>
                <div class="text-overflow" @dblclick="enableEditHistoryRow(scope.row)" :title="scope.row.remark">{{
                  scope.row.remark || '-' }}</div>
              </template>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="140" align="center">
            <template #default="scope">
              <template v-if="scope.row._editing">
                <el-button type="primary" size="small" @click="saveHistoryRow(scope.row)"
                  :loading="scope.row._saving">保存</el-button>
                <el-button size="small" @click="cancelHistoryRow(scope.row)">取消</el-button>
              </template>
              <template v-else>
                <el-button link type="primary" size="small" @click="enableEditHistoryRow(scope.row)">编辑</el-button>
              </template>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
  </div>
</template>

<script setup name="EditContractReceive" lang="ts">
import { parseTime } from '@/utils/ruoyi';
import { listProConReceive, addProConReceive, updateProConReceive } from '@/api/project/conReceive';
import { ProConReceiveVO, ProConReceiveForm } from '@/api/project/conReceive/types';
import { listProReceiveMoney } from '@/api/project/receive';
import { ConReceiveStatisticVO } from '@/api/project/init/contract/types';
import { listForReceive } from '@/api/project/init/proInfo';
import MoneyInput from '@/components/MoneyInput/index.vue';
import PageHeader from '@/views/project/components/PageHeader/index.vue';
import * as echarts from 'echarts/core';
import { LineChart } from 'echarts/charts';
import { TitleComponent, TooltipComponent, LegendComponent, GridComponent } from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';

echarts.use([LineChart, TitleComponent, TooltipComponent, LegendComponent, GridComponent, CanvasRenderer]);

const { proxy } = getCurrentInstance();
const router = useRouter();

// 字典数据
const { pro_receive_is_arrive, pro_receive_node_status } = toRefs<any>(proxy?.useDict('pro_receive_is_arrive', 'pro_receive_node_status'));

// 合同数据 - 从路由状态获取
const contractData = ref<ConReceiveStatisticVO | null>(null);
// 安全读取后端扩展统计字段，避免类型缺失导致的报错
const getStat = (key: string): number => {
  const data: any = contractData.value || {};
  const val = data?.[key];
  return Number(val) || 0;
};

// 历史回款记录相关
const historyReceiveList = ref<ProConReceiveVO[]>([]);
const historyLoading = ref(false);
const historyCollapsed = ref(false);
const historyChartRef = ref<HTMLDivElement | null>(null);
let historyChart: echarts.ECharts | null = null;

// 到达回款节点相关（已移除已达节点列表展示与加载）

// 项目回款信息层级查看相关
const projectList = ref<any[]>([]);
const projectLoading = ref(false);

/**
 * 展开/收起项目详情
 */
const toggleProjectExpand = async (project: any) => {
  project.expanded = !project.expanded;
  if (project.expanded && (!project.receiveList || project.receiveList.length === 0)) {
    await loadProjectReceiveList(project);
  }
};

// 已移除未使用的项目行行类名与行点击处理函数（使用显式展开按钮）

/**
 * 加载项目回款信息层级
 */
const loadProjectReceiveHierarchy = async (contractId: string | number) => {
  projectLoading.value = true;
  try {
    const res = await listForReceive(contractId);
    const list = res.data || [];
    // 注入前端所需的临时属性
    projectList.value = list.map((item: any) => ({
      ...item,
      expanded: false,
      receiveLoading: false,
      receiveList: []
    }));
    // 默认展开第一个项目并加载其回款节点
    if (projectList.value.length > 0) {
      projectList.value[0].expanded = true;
      await loadProjectReceiveList(projectList.value[0]);
    }
  } catch (error) {
    console.error('加载项目回款信息层级失败:', error);
    ElMessage.error('加载项目回款信息层级失败');
  } finally {
    projectLoading.value = false;
  }
};

/**
 * 加载指定项目的回款节点列表
 */
const loadProjectReceiveList = async (project: any) => {
  if (!project?.proId) return;
  project.receiveLoading = true;
  try {
    const res = await listProReceiveMoney({ proId: project.proId });
    // 映射后端VO到前端展示字段（使用 nodeLeadersName 对应“收款负责人”）
    project.receiveList = (res.data || []).map((it: any) => ({
      ...it
    }));
  } catch (e) {
    console.error('加载回款节点失败:', e);
    ElMessage.error('加载回款节点失败');
    project.receiveList = [];
  } finally {
    project.receiveLoading = false;
  }
};

/**
 * 回款节点行样式（预留编辑态样式占位）
 */
const receiveRowClassName = ({ row }: { row: any }) => {
  return row?.isEditing ? 'editing-row' : '';
};

// 历史记录表行样式（参考计划编辑页：编辑态高亮）
const historyRowClassName = ({ row }: { row: any }) => (row?._editing ? 'editing-row' : '');

// 上次填报的收款情况及下一步计划
const lastReceiveCase = ref('');

// 表单相关
const receiveFormRef = ref<ElFormInstance>();
const saveReceiveLoading = ref(false);

const receiveForm = ref<ProConReceiveForm>({
  conId: undefined,
  receiveStatus: '',
  receiveNodes: '',
  receivedAmount: 0,
  receiveLeaders: '',
  isArrive: '',
  proLeadersName: '',
  proPresidentsName: '',
  arrivedNodeAmount: 0,
  latestReceiveCase: '',
  surplusAmount: 0,
  remark: '',
  receiveIds: '',
  noReceiveAmount: 0
});

const receiveFormRules = {
  // 移除所有必填验证规则，改为非必填
};

/**
 * 格式化金额
 */
const formatAmount = (amount: number | string) => {
  if (amount === null || amount === undefined) return '0.00';
  return Number(amount).toLocaleString('zh-CN', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  });
};

/**
 * 初始化页面数据
 */
const initPageData = () => {
  // 从路由状态获取合同数据
  const routeState = history.state;
  if (routeState && routeState.contractData) {
    contractData.value = routeState.contractData;
    initFormData();
    loadHistoryReceiveRecords(contractData.value.id).then(() => renderHistoryChart());
    loadProjectReceiveHierarchy(contractData.value.id);
  } else {
    // 如果没有路由状态数据，则从URL参数获取并提示返回
    ElMessage.error('缺少合同数据，请从列表页面进入');
    router.back();
  }
};

/**
 * 初始化表单数据
 */
const initFormData = () => {
  if (!contractData.value) return;

  receiveForm.value = {
    conId: contractData.value.id,
    receiveStatus: '',
    receiveNodes: '',
    receivedAmount: Number(contractData.value.receivedAmount) || 0,
    receiveLeaders: contractData.value.receiveLeadersName || '',
    isArrive: contractData.value.isArrive || '',
    proLeadersName: contractData.value.proLeadersName || '',
    proPresidentsName: contractData.value.proPresidentsName || '',
    arrivedNodeAmount: Number(getStat('arrivedNodeAmount')) || 0,
    latestReceiveCase: '',
    surplusAmount: getStat('surplusConAmount'),
    remark: '',
    receiveIds: '',
    noReceiveAmount: Number(getStat('noReceiveAmount')) || 0
  };

  // 计算剩余应收金额的默认值
  calculateSurplusAmount();
};

/** 加载历史回款记录 */
const loadHistoryReceiveRecords = async (contractId: string | number) => {
  historyLoading.value = true;
  try {
    const params: any = {
      conId: contractId
    };
    const res = await listProConReceive(params);
    historyReceiveList.value = res.data || [];

    // 设置上次填报的收款情况及下一步计划
    if (historyReceiveList.value.length > 0) {
      // 后端已按创建时间降序排列，直接取第一条记录即可
      const latestRecord = historyReceiveList.value[0];
      lastReceiveCase.value = latestRecord.latestReceiveCase || '';
    } else {
      lastReceiveCase.value = '';
    }
  } catch (error) {
    console.error('加载历史回款记录失败:', error);
    ElMessage.error('加载历史回款记录失败');
    lastReceiveCase.value = '';
  } finally {
    historyLoading.value = false;
  }
};

/** 开启历史记录行编辑 */
const enableEditHistoryRow = (row: any) => {
  if (!row) return;
  if (!row._original) row._original = JSON.parse(JSON.stringify(row));
  row._editing = true;
};

/** 取消历史记录行编辑 */
const cancelHistoryRow = (row: any) => {
  if (!row) return;
  if (row._original) {
    const copy = { ...row._original };
    Object.keys(row).forEach((k) => delete (row as any)[k]);
    Object.assign(row, copy);
  }
  row._editing = false;
  row._saving = false;
};

/** 保存历史记录行（仅保存可编辑字段） */
const saveHistoryRow = async (row: any) => {
  try {
    row._saving = true;
    const payload: ProConReceiveForm = {
      id: row.id,
      conId: row.conId,
      receiveStatus: row.receiveStatus,
      arrivedNodeAmount: row.arrivedNodeAmount,
      surplusAmount: row.surplusAmount,
      latestReceiveCase: row.latestReceiveCase,
      remark: row.remark,
      noReceiveAmount: row.noReceiveAmount
    } as any;
    if (payload.id) {
      await updateProConReceive(payload);
      ElMessage.success('历史记录保存成功');
    } else {
      await addProConReceive(payload);
      ElMessage.success('历史记录新增成功');
    }
    // 刷新表格与图表
    if (contractData.value) {
      await loadHistoryReceiveRecords(contractData.value.id);
      renderHistoryChart();
    }
  } catch (e) {
    ElMessage.error('保存失败');
  } finally {
    row._editing = false;
    row._saving = false;
  }
};


/** 渲染回款统计变化图表 */
const renderHistoryChart = () => {
  if (!historyChartRef.value) return;
  if (!historyChart) {
    historyChart = echarts.init(historyChartRef.value);
  }
  const times = historyReceiveList.value.map((x: any) => parseTime(x.createTime, '{y}-{m}-{d}'));
  const received = historyReceiveList.value.map((x: any) => Number(x.receivedAmount) || 0);
  const arrived = historyReceiveList.value.map((x: any) => Number(x.arrivedNodeAmount) || 0);
  const surplus = historyReceiveList.value.map((x: any) => Number(x.surplusAmount) || 0);

  const option = {
    tooltip: { trigger: 'axis' },
    legend: { data: ['已收款金额', '已达节点总金额', '剩余合同金额'] },
    grid: { left: 40, right: 20, top: 40, bottom: 40 },
    xAxis: { type: 'category', data: times },
    yAxis: { type: 'value' },
    series: [
      { name: '已收款金额', type: 'line', data: received, smooth: true },
      { name: '已达节点总金额', type: 'line', data: arrived, smooth: true },
      { name: '剩余合同金额', type: 'line', data: surplus, smooth: true }
    ]
  } as any;
  historyChart.setOption(option);
};

// 已移除：到达回款节点加载与金额自动计算逻辑

/** 计算剩余应收金额 */
const calculateSurplusAmount = () => {
  // 不可编辑：始终采用合同详情中的“剩余合同金额”
  receiveForm.value.surplusAmount = getStat('surplusConAmount');
};

// 去除联动编辑：该字段不可编辑，保存时与合同详情保持一致

/** 保存回款信息 */
const saveReceiveInfo = async () => {
  try {
    await receiveFormRef.value?.validate();
    saveReceiveLoading.value = true;

    const formData = { ...receiveForm.value };

    // 始终按合同详情中的“剩余合同金额”保存（不可编辑）
    formData.surplusAmount = getStat('surplusConAmount');

    // 判断是新增还是更新
    if (formData.id) {
      await updateProConReceive(formData);
      ElMessage.success('回款信息更新成功');
    } else {
      await addProConReceive(formData);
      ElMessage.success('回款信息添加成功');
    }

    // 保存成功后刷新当前页面数据并重置表单，不跳转
    if (contractData.value) {
      initFormData();
      await Promise.all([
        loadHistoryReceiveRecords(contractData.value.id),
        loadProjectReceiveHierarchy(contractData.value.id)
      ]);
      // 重置校验状态
      receiveFormRef.value?.clearValidate?.();
      // 重绘图表
      renderHistoryChart();
    }

  } catch (error) {
    console.error('保存回款信息失败:', error);
    ElMessage.error('保存回款信息失败');
  } finally {
    saveReceiveLoading.value = false;
  }
};

/** 重置表单 */
const handleReset = () => {
  // 重置所有可编辑字段为空
  receiveForm.value.receiveStatus = '';
  receiveForm.value.arrivedNodeAmount = 0;
  receiveForm.value.surplusAmount = 0;
  receiveForm.value.latestReceiveCase = '';
  receiveForm.value.remark = '';

  // 清除表单验证状态
  receiveFormRef.value?.clearValidate();

  ElMessage.success('表单已重置');
};

onMounted(() => {
  initPageData();
  window.addEventListener('resize', () => historyChart?.resize?.());
});
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

/* 金额文本样式 */
.amount-text {
  font-weight: bold;
  font-size: 14px;
}

.contract-amount {
  color: #1f2937;
}

.received-amount {
  color: #059669;
}

/* 已达节点金额（信息/蓝色） */
.arrived-amount {
  color: #2563eb;
}

.remaining-amount {
  color: #f59e0b;
}

/* 卡片头部样式 */
.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  color: #1f2937;
}

.card-header .el-icon {
  color: #409eff;
  font-size: 16px;
}

/* 可收起卡片头部 */
.collapsible {
  display: flex;
  justify-content: space-between;
  align-items: center;
  cursor: pointer;
}

/* ================== 项目回款信息层级查看：样式（参考计划页面） ================== */
/* 容器 */
.project-list {
  width: 100%;
}

/* 顶部表头 */
.list-header {
  display: flex;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  border: 1px solid #e4e7ed;
  border-radius: 8px 8px 0 0;
  padding: 12px 0;
  font-weight: 600;
  color: #303133;
  font-size: 14px;
}

.header-cell {
  padding: 0 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-right: 1px solid #e4e7ed;
  text-align: center;
}

.header-cell.left-align {
  justify-content: flex-start;
  text-align: left;
}

.header-cell:last-child {
  border-right: none;
}

/* 列宽定义（与模板列顺序匹配） */
.header-name {
  flex: 2 0 0;
}

.header-number {
  flex: 1 0 0;
}

.header-president {
  flex: 1 0 0;
}

.header-leader {
  flex: 1 0 0;
}

.header-receive-leader {
  flex: 1 0 0;
}

.header-status {
  flex: 0 0 150px;
  width: 150px;
}

.header-action {
  flex: 0 0 200px;
  width: 200px;
}

/* 项目项容器 */
.project-item {
  border: 1px solid #e4e7ed;
  border-top: none;
}

.project-item:last-child {
  border-radius: 0 0 8px 8px;
}

/* 项目主行 */
.project-row {
  display: flex;
  background-color: #ffffff;
  transition: all 0.2s ease;
  cursor: pointer;
  min-height: 56px;
}

.project-row:hover {
  background-color: #f5f7fa;
}

.project-cell {
  padding: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-right: 1px solid #f0f0f0;
  font-size: 14px;
  text-align: center;
}

.project-cell.left-align {
  justify-content: flex-start;
  text-align: left;
}

.project-cell:last-child {
  border-right: none;
}

/* 单元格列宽与表头一致 */
.project-name {
  flex: 2 0 0;
}

.project-number {
  flex: 1 0 0;
}

.project-president {
  flex: 1 0 0;
}

.project-leader {
  flex: 1 0 0;
}

.project-receive-leader {
  flex: 1 0 0;
}

.project-status {
  flex: 0 0 150px;
  width: 150px;
}

.project-action {
  flex: 0 0 200px;
  width: 200px;
}

/* 展开按钮（参考计划页面样式） */
.expand-button {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  padding: 8px 12px;
  border: 2px solid #d1d5db;
  border-radius: 8px;
  background-color: #ffffff;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 14px;
  font-weight: 500;
  color: #6b7280;
  min-width: 96px;
}

.expand-button:hover {
  border-color: #409eff;
  background-color: #f0f9ff;
  color: #409eff;
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(64, 158, 255, 0.2);
}

.expand-button.expanded {
  border-color: #409eff;
  background-color: #409eff;
  color: #ffffff;
}

.expand-button.expanded:hover {
  background-color: #3b82f6;
  border-color: #3b82f6;
}

.expand-text {
  font-weight: 600;
  letter-spacing: 0.5px;
}

.expand-arrow {
  display: flex;
  align-items: center;
  justify-content: center;
  transition: transform 0.3s ease;
}

.expand-arrow.rotated {
  transform: rotate(180deg);
}

.expand-arrow {
  width: 16px;
  height: 16px;
}

/* 展开内容容器 */
.expand-content {
  padding: 16px;
  background: #f8f9fa;
  border: 2px solid #409eff;
  border-radius: 8px;
  margin: 10px 0;
  position: relative;
  animation: slideDown 0.3s ease-out;
}

@keyframes slideDown {
  from {
    opacity: 0;
    max-height: 0;
    padding: 0 16px;
  }

  to {
    opacity: 1;
    max-height: 1000px;
    padding: 16px;
  }
}

/* 二层：回款节点头部 */
.receive-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 10px;
}

.receive-header-left {
  display: flex;
  align-items: center;
  gap: 8px;
}

.receive-icon {
  font-size: 18px;
  color: #409eff;
}

.receive-title {
  font-size: 15px;
  font-weight: 600;
  color: #2c3e50;
}

/* 二层：表格样式优化 */
.receive-list {
  border-radius: 8px;
  overflow: hidden;
  border: 1px solid #ebeef5;
  background-color: #ffffff;
}

.receive-table-fixed :deep(.el-table) {
  table-layout: fixed;
}

.receive-table-fixed :deep(.el-table__body td:nth-child(1)) {
  width: 66.67% !important;
  min-width: 66.67% !important;
}

.receive-table-fixed :deep(.el-table__body td:nth-child(4)) {
  width: 33.33% !important;
  min-width: 33.33% !important;
}

.receive-table-fixed :deep(.el-table__header th:nth-child(1)) {
  width: 66.67% !important;
  min-width: 66.67% !important;
}

.receive-table-fixed :deep(.el-table__header th:nth-child(4)) {
  width: 33.33% !important;
  min-width: 33.33% !important;
}

.receive-list :deep(.el-table__header-wrapper) th {
  background-color: #f5f7fa;
  color: #374151;
  font-weight: 600;
}

.receive-list :deep(.el-table__row:hover) {
  background-color: #f5f7fa;
}

/* 付款节点标题：固定列宽内，最多两行，超出省略 */
.node-title-text {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: normal;
  word-break: break-word;
}

.two-line-clamp {
  -webkit-line-clamp: 2;
  line-clamp: 2;
}

.receive-list :deep(.editing-row) {
  background-color: var(--el-color-primary-light-9);
}

.receive-list :deep(.editing-row td) {
  background-color: var(--el-color-primary-light-9) !important;
}

/* 历史记录编辑态高亮（与计划页面一致的编辑行视觉） */
.history-record-card :deep(.editing-row) {
  background-color: var(--el-color-primary-light-9);
}

.history-record-card :deep(.editing-row td) {
  background-color: var(--el-color-primary-light-9) !important;
}

/* 文本溢出统一处理 */
.text-overflow {
  display: inline-block;
  max-width: 100%;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  vertical-align: top;
  text-align: center;
  width: 100%;
}

/* 历史记录“最新收款情况”居左显示 */
.text-overflow.left-text {
  text-align: left;
}

.left-align .text-overflow {
  text-align: left;
}

/* 空状态 */
.empty-state {
  padding: 20px 0;
}

/* 项目回款信息层级查看样式 */
/* 移除未使用的旧样式块：.project-table/.receive-list-container/.receive-list-header/.receive-table */

.no-data {
  padding: 20px 0;
  text-align: center;
  color: #909399;
  font-size: 14px;
}

.no-data .el-empty__description {
  color: #909399;
}

/* 合同信息样式 */
.contract-name-text {
  color: #0ea5e9;
  font-weight: 600;
}

.contract-number-text {
  color: #a855f7;
  font-weight: 600;
}

/* 卡片间距 */
.box-card {
  border-radius: 12px !important;
}

/* 统一使用 mb-6 (24px) 控制各板块间距，避免被覆盖 */

.history-record-card .el-table {
  margin-top: 0;
}

.edit-form-card .el-form {
  padding: 20px 0;
}

/* 信息分组样式 */
.info-section {
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 20px;
  background: #f9fafb;
}

.edit-section {
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 20px;
  background: #ffffff;
  position: relative;
  /* 让内部绝对定位参照本块 */
  padding-bottom: 72px;
  /* 预留空间给右下角按钮 */
}

.form-actions {
  display: flex;
  justify-content: flex-end;
}

.form-actions-bottom {
  position: absolute;
  right: 16px;
  bottom: 16px;
  margin: 0;
}

/* 保留原有的表单分组样式，以防其他地方还在使用 */
.form-section {
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  padding: 12px 12px 4px 12px;
  margin-bottom: 16px;
}

.form-section.readonly {
  background: #f9fafb;
}

.form-section.editable {
  background: #ffffff;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  color: #374151;
  padding: 4px 0 12px 0;
}

.section-title .el-icon {
  color: #409eff;
}

/* ECharts 容器 */
.history-chart {
  width: 100%;
  height: 260px;
  margin-bottom: 12px;
}

/* Element Plus 组件样式覆盖 */
:deep(.el-descriptions__label) {
  font-weight: 600;
  color: #374151;
}

:deep(.el-descriptions__content) {
  color: #1f2937;
}

/* 人员姓名左对齐显示（覆盖描述项默认样式） */
.name-left {
  display: inline-block;
  width: 100%;
  text-align: left;
}

/* 已达回款节点下拉框选项样式 */
/* 移除与“已达回款节点”下拉相关的样式 */

/* 响应式设计 */
@media (max-width: 768px) {
  .app-container {
    padding: 10px;
  }

  :deep(.el-descriptions) {
    --el-descriptions-table-border: 1px solid var(--el-border-color-lighter);
  }

  :deep(.el-form-item__label) {
    font-size: 13px;
  }
}
</style>
